<template>
  <div class="container">
    <div class='tools_container'>
      <div class="tools">
        <div>
          <el-button @click="queryList" type="primary">
            刷新
          </el-button>
          <el-button @click="commitUpload" type="primary">
            提交结果
          </el-button>
        </div>
      </div>

    </div>
    <div class="margin-f5-10px"></div>


    <div class="table_message">
      <el-button @click="handleGoHandler('13')" type="info">学号不存在异常:{{ info.codeNotExistNumber }}张</el-button>
      <span style="display: inline-block;width: 10px"></span>
      <el-button @click="handleGoHandler('11')" type="info">学号重复异常: {{ info.codeRepeatNumber }}张</el-button>
      <span style="display: inline-block;width: 10px"></span>
      <el-button @click="handleGoHandler('20')" type="info">客观题异常: {{ info.objectiveNumber }}张</el-button>
      <span style="display: inline-block;width: 10px"></span>
    </div>
    <div class="table_message">
      <el-form label-position="left" :inline="true">
        <el-form-item label-width="30" label="考号:">
          <el-input v-model="select.examCode" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label-width="30" label="状态:">
          <el-select v-model="select.status">
            <el-option label="全部" value=""></el-option>
            <el-option label="已上传" value="ok"></el-option>
            <el-option label="未上传" value="no"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <el-table
        :data="tableData"
        :header-cell-style="{height: '54px',background: '#f5f5f5',fontSize: '14px', color: '#3D3D3D'}"
        style="width: 100%">

      <el-table-column
          prop="createTime"
          label="接收图片"
      >
        <template slot-scope="{row}">
          <el-image lazy v-if="row.targetUrl" :src="row.targetUrl"
                    :preview-src-list="[row.targetUrl]"
                    style="width:100px;height: 100px"
          >
          </el-image>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="className"
          label="班级"
      >
      </el-table-column>
      <el-table-column
          prop="studentName"
          label="学生"
      >
      </el-table-column>
      <el-table-column
          prop="examCode"
          label="学生考号"
      >
      </el-table-column>

      <el-table-column
          prop="status"
          label="上传状态"
      >
        <template slot-scope="{row}">
          <span>{{parseStatusDic[row.status]}}</span>
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="200">
        <template slot-scope="{row}">
          <el-button type="text" size="small" @click="look(row)">查看</el-button>
          <el-button type="text" size="small" @click="handleDelete(row)">删除答题卡</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.current"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="page.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
    </el-pagination>

    <el-drawer
        size="80%"
        title="解析答题卡"
        :visible.sync="drawer"
        direction="rtl"
        :before-close="handleClose">
      <div style="width: 100%;height: 100%">
        <scan-ui :config="config"
                 @closeParseVisible="closeParseVisible"
                 @refreshRecord="queryList"
        ></scan-ui>
      </div>
    </el-drawer>
    <el-dialog title="请选择答题卡来源"
               :visible.sync="parseVisible"
               @open="parseOpen">
      <div>
        <el-button type="success" round @click="directoryClick()">目录</el-button>
      </div>
    </el-dialog>
    <div
        @click="drawer=true"
        v-show="config != null && !drawer"

        style="z-index:10;top:50%;border-radius: 50%;width: 50px;height: 50px;position: fixed;background: #4187ff;line-height: 50px;text-align: center;color: white;right: 20px">
      继续
    </div>

    <el-drawer
        title="异常处理"
        size="80%"
        :visible.sync="showHandler"
        :before-close="handleErrorDrawerClose"
        :direction="'btt'">
      <div>
        <HandleCode :current-code="currentCode" :work-id="workId" v-if="currentCode.startsWith('1')"></HandleCode>
        <HandleQuestion :current-code="currentCode" :work-id="workId" v-else-if="currentCode.startsWith('2')"></HandleQuestion>

      </div>
    </el-drawer>
    <el-drawer
        title="详情"
        :visible.sync="showDetail"
        :direction="'rtl'">
      <template v-if="detail">
      <el-form inline v-for="item in detail.items" :key="item.itemId">
          <el-form-item :label="item.paperIndex + '.'">
            <el-image lazy style="width: 150px" :src="item.file[0]" :preview-src-list="item.file"></el-image>
          </el-form-item>
          <el-form-item v-if="item.answer">
            <el-input v-model="item.answer"></el-input>
          </el-form-item>
      </el-form>
      </template>
      <span v-else></span>
    </el-drawer>
  </div>
</template>

<script>
import HandleCode from "@/views/sheet/uploadHandle.vue";
import HandleQuestion from "@/views/sheet/uploadQuestionHandle.vue";
export default {
  name: "uploadPhotos",
  components: {HandleCode, HandleQuestion},

  data() {
    return {
      showDetail: false,
      detail: null,
      currentCode: '',
      selectScanner: false,
      selectIndex: '',
      scanners: [],
      parseStatusDic: new Proxy({
        'no': '未上传',
        'ok': '已上传'
      }, {
        get(target, prop) {
          let value = target[prop];
          if (value) {
            return value
          }
          return ''
        },
      }),
      showHandler: false,
      info: {},
      tableData: [],
      parse: "",
      parseVisible: false,
      parseData: [],
      fileTableData: [],
      config: null,
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      drawer: false,
      workId: null,
      work: null,
      fileList: [],
      scanDirectory: '',
      select: {
        status: '',
        examCode: '',
      }
    }
  },
  watch: {
    'select': {
      deep: true,
      handler: function () {
        this.queryList()
      },
    }
  },
  created() {

  },

  mounted() {
    this.workId = this.$route.query.workId
    this.queryWork().then(() => {
      this.queryList()
    })
  },
  methods: {
    handleDelete(row) {
      this.$confirm('确认删除？')
          .then(_ => {
            this.deleteItem(row)
          })
          .catch(_ => {
          });

    },
    async deleteItem(row) {
      const res = await this.$api.deleteSheet({
        uploadId: row.uploadId
      })
      if (res.code !== 200) {
        this.$message.warning(res.message)
        return
      }
      this.queryList()
    },
    handleErrorDrawerClose() {
      this.currentCode = ''
      this.showHandler = false
      this.queryList()
    },
    handleGoHandler(code) {
      this.currentCode = code
      this.showHandler = true

    },
    closeParseVisible() {
      this.drawer = false
      this.queryList()
    },
    async directoryClick(dir) {

      if (this.work == null) {
        await this.queryWork()
        if (this.work == null) {
          this.$error("获取考试信息失败")
          return
        }
      }
      if (!!!dir) {
        let res = null;
        let loading = this.$fastLoading();

        try {
          res = await this.$HttpPost.desktop.getDirectoryPath.request({})
        } finally {
          loading.close()
        }
        if (res.code !== 200) {
          this.$error('请重新打开')
          return
        }
        if (res.data === '') {
          this.parseVisible = false
          return
        }
        this.scanDirectory = res.data
      } else {
        this.scanDirectory = dir
      }
      if (this.parseData.length === 0) {
        const loading = this.$fastLoading()

        try {
          await this.queryParseList();
        } finally {
          loading.close()
        }
      }
      this.parseVisible = false
      if (this.parseData.length === 0) {
        this.$error("获取答题卡模板失败")
        return
      }
      let item = this.parseData[this.parseData.length - 1];
      this.config = {
        parseItem: item,
        parseImg: this.$api.getTemplateUrl(item.id),
        paperId: item.paperId,
        templateId: item.id,
        workId: this.work.id,
        path: this.scanDirectory
      };
      this.drawer = true
    },
    async commitUpload() {
      let elLoadingComponent = this.$fastLoading();
      try {
        let res = await this.$api.commitUpload({
          workId: this.work.id
        })

      } finally {
        elLoadingComponent.close()
      }
      this.queryParseList();
    },
    goHome() {
      window.location.href = 'http://question.clovsoft.com'
    },
    handleSelectParse(parse) {
      this.parseVisible = false;
      this.parse = parse;
    },
    parseOpen() {
      this.queryParseList()
    },
    handleFileChange(file, fileList) {
      this.fileList = fileList
    },
    async queryParseTotal() {
      let res = await this.$api.editUploadTotal({
        workId: this.work.id
      })
      if (res.code !== 200) {
        this.$message.warning(res.message)

        return
      }
      this.info = res.data
    },
    async queryParseList() {

      let res = await this.$api.parseOkList({
        workId: this.work.id
      })
      if (res.code !== 200) {
        this.$message.warning(res.message)

        return;
      }
      this.parseData = res.data

    },
    async queryWork() {

      let res = await this.$api.workOne({
        id: this.workId
      })
      if (res.code !== 200) {
        this.$message.warning(res.message)

        return
      }
      this.work = res.data

    },
    handleClose(done) {
      done();
    },
    handleSizeChange() {
      this.queryList()
    },
    handleCurrentChange(current) {
      // console.log(current)
      this.page.current = current
      this.queryList()
    },
    async queryList() {
      this.queryParseTotal()
      let elLoadingComponent = this.$fastLoading();
      try {
        let res = await this.$api.examStudentUploadPage({
          current: this.page.current,
          size: this.page.size,
          data: {
            workId: this.workId,
            status: this.select.status,
            examCode: this.select.examCode
          }
        })
        if (res.code !== 200) {
          return
        }
        this.tableData = res.data.data
        this.page.total = res.data.total
      } finally {
        elLoadingComponent.close()
      }

      // console.log(this.page.total)
    },
    async look(row) {
      let loading = this.$fastLoading();
      try {
        const res = await this.$api.uploadDetail({
          uploadId: row.uploadId
        })
        if (res.code !== 200) {
          this.$message.warning("查询失败")
          return
        }
        this.detail = res.data
        this.showDetail = true
      } catch (e) {
      } finally {
        loading.close()
      }
    }
  }
}
</script>

<style scoped type="less">
.container {
  padding: 31px 34px;

  box-sizing: border-box;
  height: 100%;
  width: 100%;
  overflow: auto;
  .margin-f5-10px {
    background: #f5f5f5;
    height: 10px;
  }
  .tools_container {
    margin-bottom: 10px;
    display: flex;
    .tools {
      .el-button {
        background: #4187FF;
        height: 32px;
      }
    }


    .tools_form {

    }
  }
  .table_message {
    margin-top: 10px;
    margin-bottom: 10px;
  }
}
</style>
